<?php
namespace app\admin\logic\admin;

use app\common\logic\AdminBase;
use app\common\model\AdminGroupModel;
use app\common\model\AdminModel;
use app\common\model\AdminMenuModel;
use think\facade\Session;

class AdminGroup extends AdminBase
{
    public function __construct()
    {
        $this->model = new AdminGroupModel();
    }

    public function get($params)
    {
        $result['one'] = parent::get($params);
        if ( ! empty($result['one']['menus'])) {
            $this->groupMenus = explode(',', $result['one']['menus']);
        }
        
        $result['menus'] = $this->buildMenuChild(0, AdminMenuModel::getAllOpenMenus());

        return $result;
    }

    public function _checkSave($params)
    {
        $params['menus'] = implode(',', $params['menus']);

        return $params;
    }

    //递归获取子菜单
    public function buildMenuChild($pid, $menuList)
    {
        $treeList = [];
        foreach ($menuList as $v) {
            if ($pid == $v['pid']) {
                $node = [
                    'id' => $v['id'],
                    'title' => $v['title'],
                ];
                if ( ! empty($v['href'])) {
                    $node['field'] = 'menus[]';
                }

                $child = $this->buildMenuChild($v['id'], $menuList);
                if (!empty($child)) {
                    $node['children'] = $child;
                }
                // todo 后续此处加上用户的权限判断
                if ( ! empty($this->groupMenus)) {
                    if (in_array($node['id'], $this->groupMenus)) {
                        $node['checked'] = true;
                    }
                }

                // 默认展开
                $node['spread'] = true;

                $treeList[] = $node;
                $node = null;
            }
        }
        return $treeList;
    }
}